package patrol.mobile.com.mobilepatrol.persenter;

import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import io.realm.Realm;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.api.ByteCallback;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.Car;
import patrol.mobile.com.mobilepatrol.manager.CarManager;
import patrol.mobile.com.mobilepatrol.utils.Compress;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.view.CarView;

/**
 * Created by apple on 17/9/27.
 */

public class CarPer {
    private CarView mView;
    String type;
    public CarPer(CarView mView, String type) {
        this.mView = mView;
        this.type = type;
    }
    public void getCars() {
        OkHttpUtils
                .post()
                .addParams("type",type)
                .url(SPUtils.get(Constants.current_ser,"") + Urls.initData)
                .build()
                .execute(new ByteCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(byte[] response, int id) {
                        try {
                            String result = Compress.decompressByteArray(response);
                            JSONObject object = new JSONObject(result);
                        if (object.getInt("code")==200){
                            CarManager.delAllCars();
                            mView.hideLoading();
                            JSONObject value = object.getJSONObject("value");
                            final JSONArray companys = value.getJSONArray("cars");
                            PatrolApp.realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {
                                    realm.createAllFromJson(Car.class, companys.toString());
                                }
                            });
                            mView.onCarSuccess("初始化车辆成功");
                        }else{
                            mView.onCarError("初始化车辆信息失败");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }
}
